package com.jin.xianyulao;

import android.app.Application;
import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.jin.xianyulao.JsonBean.JsonBean;
import com.jin.xianyulao.JsonBean.JsonResponseBean;
import com.jin.xianyulao.JsonBean.ResultList;

import java.io.File;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

public class MainHook implements IXposedHookLoadPackage {
    private String[] searchList = {"thinkpad全新","thinkbook全新","think全新"};
    private int i,a;
    private boolean b = true;
    private Object doDec;
    @Override
    public void handleLoadPackage(XC_LoadPackage.LoadPackageParam p1) throws Throwable{
        XposedHelpers.findAndHookMethod(Application.class, "attach", Context.class, new XC_MethodHook() {
            @Override
            protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                super.beforeHookedMethod(param);
            }

            @Override
            protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                super.afterHookedMethod(param);
                ClassLoader classLoader = ((Context)param.args[0]).getClassLoader();
                XposedHelpers.findAndHookMethod("mtopsdk.mtop.domain.MtopRequest", classLoader, "getData", new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                    }

                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                        //XposedBridge.log("Hook getData()\n"+param.getResult().toString());
                        Gson gson = new Gson();
                        JsonBean search = gson.fromJson(""+param.getResult(),JsonBean.class);

                        if (search.getKeyword() != null){
                            Log.i("XposedXYL",gson.toJson(search));
                            search.setKeyword(searchList[a]);
                            search.setFromCombo("Filter");
                            search.setFromFilter(true);
                            search.setSearchReqFromActivatePagePart("historyItem");
                            search.setPropValueStr("2000.0","40000.0","1");
                            search.setRowsPerPage(30);
                            search.setClientModifiedCpvNavigatorJson("{\"tabList\":[],\"errorInfo\":\"keywordsQpSecondaryCatList is empty\",\"fromClient\":false}");
                            param.setResult(gson.toJson(search));
                            i++;
                            if (i%3 == 0){
                                i =0;
                                a++;
                                Log.i("XposedXYL",""+a);
                                if (a == 3){
                                    a = 0;
                                }
                            }
                        }

                    }
                });

                XposedHelpers.findAndHookMethod("mtopsdk.mtop.domain.MtopResponse", classLoader, "getDataJsonObject", new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                    }

                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                        //Log.i("XposedXYL",""+param.getResult());
                        //writeTxtToFile(""+param.getResult());
                        Gson gson = new Gson();
                        JsonResponseBean jsonResponseBean = gson.fromJson(""+param.getResult(),JsonResponseBean.class);
                        if (jsonResponseBean.getCustomButtonInfoDO() != null){
                            //Log.i("XposedXYL",""+param.getResult());
                            writeTxtToFile(""+param.getResult()+"\n\n\n");
                            if (b){
                                b = false;
                                List<ResultList> resultList = jsonResponseBean.getResultList();
                                //writeTxtToFile(""+gson.toJson(resultList));
                                Log.i("XposedXYL",doJson(resultList));
                            }else {
                                b = true;
                            }
                        }
                    }
                });

                XposedHelpers.findAndHookMethod("com.taobao.android.remoteobject.easy.network.interceptor.MtopDecodeInterceptor", classLoader,"doDecode", String.class, new XC_MethodHook() {
                    @Override
                    protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                        super.beforeHookedMethod(param);
                        if(doDec == null){
                            doDec = param.thisObject;
                        }
                    }

                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        super.afterHookedMethod(param);
                        //Log.i("XposedXYL","666"+param.getResult());
                    }
                });
            }
        });

    }

    public void writeTxtToFile(String str){
        String strContent = str + "\r\n";
        try {
            File file = new File("/sdcard/log.txt");
            if (!file.exists()){
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file,"rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        }catch (Exception e){

        }
    }

    public String doJson(List<ResultList> json){
        JsonArray rtArr = new JsonArray();
        JsonObject ob = new JsonObject();
        Gson gson = new Gson();
        for (int c = 1; c < json.size();c++){
            //Log.i("XposedXYL",""+resultList.get(c).getData().getItem().getMain().getExContent().getTitle());
            //Log.i("XposedXYL",""+json.get(c).getData().getItem().getMain().getExContent().getDetailParams().getUserNick());
            Map<String,Object> ret = new HashMap<>();
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("昵称",json.get(c).getData().getItem().getMain().getExContent().getDetailParams().getUserNick());
            jsonObject.addProperty("标题",json.get(c).getData().getItem().getMain().getExContent().getDetailParams().getTitle());
            jsonObject.addProperty("价格",json.get(c).getData().getItem().getMain().getExContent().getDetailParams().getSoldPrice());
            jsonObject.addProperty("关注",json.get(c).getData().getItem().getMain().getClickParam().getArgs().getTagname());
            //ret.put("关注",json.get(c).getData().getItem().getMain().getClickParam().getArg);
            jsonObject.addProperty("发布时间",stampToDate(json.get(c).getData().getItem().getMain().getClickParam().getArgs().getPublishTime()));
            jsonObject.addProperty("商品id",json.get(c).getData().getItem().getMain().getClickParam().getArgs().getItem_id());
            //Log.i("XposedXYL",getDoDecode(json.get(c).getData().getItem().getMain().getExContent().getJump2XianYuHao().getClickParam().getArgs().getSeller_id()));
            rtArr.add(jsonObject);
        }
        ob.add("data",rtArr);
        return gson.toJson(ob);
    }
    public String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    public String getDoDecode(String str){
        return (String) XposedHelpers.callMethod(doDec,"doDecode",str);
    }

}
